package wap.queue.impl;

import java.util.HashSet;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import wap.queue.IQueue;

/**
 * @描述：装载gz文件;不在共享队列中做线程控制，只做共享锁
 * @作者：hongxingfan
 * @时间：2014年9月19日 上午9:42:44
 */
public class QueueWapImpl<E> implements IQueue<E> {

	private static final int QUEUE_SIZE = 4;
	private final BlockingQueue<E> queue = new ArrayBlockingQueue<E>(QUEUE_SIZE, true);
	private final HashSet<E> dealedSet = new HashSet<E>();
	private final Lock lock = new ReentrantLock(true);

	@Override
	public boolean add(E element) {
		try {
			lock.lock();
			if (queueSize() >= QUEUE_SIZE) {
				return false;
			}
			if (!this.dealedSet.contains(element)) {
				boolean flag = this.queue.add(element);
				this.dealedSet.add(element);
				return flag;
			}
			return false;
		} finally {
			lock.unlock();
		}
	}

	// 当get操作的线程超过10次没有获取到数据就自动退出
	@Override
	public E get() {
		try {
			lock.lock();
			return this.queue.poll();
		} finally {
			lock.unlock();
		}
	}

	@Override
	public boolean isEmpty() {
		return queue.isEmpty();
	}

	@Override
	public int queueSize() {
		return queue.size();
	}

	@Override
	public int hashSize() {
		return this.dealedSet.size();
	}
}
